import $Notice from 'heyui/lib/plugins/notice'
import axios from 'axios'
import router from './router'
import md5 from 'js-md5'

const api = (method,path,param,app=false) => {
	return new Promise((resolve, reject) => {
		let paramsformat,dataformat;
		if(method == 'GET'){
			paramsformat = Object.assign({path:path},param)//微擎
			//读缓存
			if(path == 'json'){
				let time = Date.parse(new Date())/1000 - 86400
				let sign = md5(path+JSON.stringify(paramsformat))
				let cache = JSON.parse(localStorage.getItem(sign) || '{}')
				if(cache.time > 0 && cache.time > time){
					resolve(cache.data)
					return
				}
			}
		}else{
			dataformat = Object.assign({path:path},param)//微擎
		}
		let url = '/web/index.php?c=site&a=entry&do=api&m=qd_market';
		if (process.env.NODE_ENV === "development") {
			url = 'https://wq.huantu.cc/app/index.php?i=2&c=entry&do=web&m=qd_market'
		}
		if(app){
			url = 'https://wq.huantu.cc/app/index.php?i=2&c=entry&a=wxapp&m=qd_market&do=api'
		}
		axios({
			headers: {'Content-Type': 'application/json'},
			method: method,
			url: url,//微擎
			params : paramsformat,
			data: dataformat
		}).then(res => {
			if(res.data.code == 200){
				if(method == 'GET'){//写缓存
					if(path == 'json'){
						let sign = md5(path+JSON.stringify(paramsformat))
						let cache = {data:res.data.data,time:Date.parse(new Date())/1000}
						localStorage.setItem(sign,JSON.stringify(cache))
					}
				}
				if(res.data.msg){
					$Notice({
						type: 'success',
						title: '成功',
						content: res.data.msg
					})
				}
			}
			if(res.data.code == 401 || res.data.code == 404){
				//localStorage.removeItem('token')
				//router.replace({path: '/login'})
				$Notice({
					type: 'error',
					title: '错误',
					content: res.data.msg
				})
				return false
			}
			if(res.data.code == 500){
				$Notice({
					type: 'error',
					title: '错误',
					content: res.data.msg
				})
			}
			resolve(res.data.data)
		}).catch((error) => {
			reject(error)
		})
	})
}
export default api